const mongoose = require("mongoose");


// 填充商品数据
async function getCommData(rows) {
  // 获取商品model,通过商品id填充商品数据
  const commoditytModel = mongoose.model('commodity');
  for (let i = 0; i < rows.length; i++) {
    const _id = rows[i].seckill_id.commodity_id;
    rows[i].seckill_id.commodity_id = await commoditytModel.findOne({ _id });
  };
  return rows;
}

const get = async ({ curPage, eachPage }) => {
  (curPage = ~~curPage), (eachPage = ~~eachPage);
  const data = {
    total: 0
  }
  // 获取model对象
  const shoppingCartModel = mongoose.model('shoppingCart');
  // 获取当前model映射的集合名存放文档总数
  data.total = await shoppingCartModel.countDocuments();
  // 获取最大页  Math.ceil向上取整
  data.maxPage = Math.ceil(data.total / eachPage);

  // 计算跳过多少条
  const skipNum = (curPage - 1) * eachPage;
  // find是异步方法，populate(填充(找到相对应的完整数据返回))  skip(跳过多少条). limit(限制范围).exec=execute(执行)  sort({排序条件})
  data.rows = await shoppingCartModel.find().skip(skipNum).populate("user_id").populate("seckill_id").limit(eachPage).sort({ _id: -1 }).exec();
  data.rows = await getCommData(data.rows);

  return data;
};

// 删除商品
const delComm = async (_id) => {
  // 获取model对象
  const shoppingCartModel = mongoose.model('shoppingCart');
  // 删除
  return await shoppingCartModel.remove({ _id });
}

// 新增商品
const addComm = async ({ user_id, seckill_id, count }) => {
  const shoppingCartModel = mongoose.model('shoppingCart');
  return await shoppingCartModel.create({ user_id, seckill_id, count });
}



// 获取新增购物车数据
const getAddCartData = async ({ user_id, seckill_id }) => {
  // 获取所用用户
  const usersModel = mongoose.model("users");
  const user = await usersModel.findOne({ _id: user_id });

  // 获取所有秒杀商品
  const seckillModel = mongoose.model("seckill");
  const seckill = await seckillModel.findOne({ _id: seckill_id }).populate("commodity_id").exec();

  return { user, seckill };
}

// 修改商品数量
const changeCount = async ({ count, _id }) => {
  const shoppingCartModel = mongoose.model('shoppingCart');
  return await shoppingCartModel.updateOne({ _id }, { count });
}

// 通过用户id查找对应购物车商品
const findCart = async (user_id) => {
  const shoppingCartModel = mongoose.model('shoppingCart');
  var data = await shoppingCartModel.find({ user_id }).populate("user_id").populate("seckill_id").sort({ _id: -1 }).exec();
  data = await getCommData(data);
  return data;
}

// 通过商品id找到整条数据
const findComm = async (_id) => {
  const commoditytModel = mongoose.model('commodity');
  return await commoditytModel.findOne({ _id });
}


module.exports = {
  get,
  delComm,
  addComm,
  changeCount,
  findCart,
  findComm,
  getAddCartData
}